package com.theexceptions.todo.view;

import com.theexceptions.todo.controller.RegisterController;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

/**
 * An Activity that manages user registration. Corresponds to the view:
 * register.xml.
 * 
 * @author TheExceptions
 */
public class RegisterActivity extends Activity {

	private static final String EMAIL_REGEX = "^[\\w\\-]+(\\.[\\w\\-]+)*@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.register);
	}

	/**
	 * Switches the layout from the register screen to the home screen when
	 * "register" is pressed
	 * 
	 * @param view Current view
	 */
	public void registerButtonClicked(View view) {
		/*
		 * JUnit tested
		 * TODO junit.framework.AssertionFailedError: User with with email bademail@45junit.com was added to database.
		 * TODO junit.framework.AssertionFailedError: User with with email 45bademail@junit.com was added to database.
		 */
		
		String name = ((EditText) this.findViewById(R.id.editText1)).getText().toString();
		String email = ((EditText) this.findViewById(R.id.editText3)).getText().toString();
		String username = ((EditText) this.findViewById(R.id.editText2)).getText().toString();
		String password = ((EditText) this.findViewById(R.id.editText4)).getText().toString();
		String passwordCheck = ((EditText) this.findViewById(R.id.editText5)).getText().toString();

		// Insure that all information was entered correctly
		if (name == null || name.equals("") || email == null || email.equals("") || username == null
				|| username.equals("") || password == null || password.equals("") || passwordCheck == null
				|| passwordCheck.equals("")) { // fields are blank
			Toast.makeText(this, "Please fill in all fields!", Toast.LENGTH_SHORT).show();

		} else if (!password.equals(passwordCheck)) { // passwords don't match
			Toast.makeText(this, "Passwords do not match!", Toast.LENGTH_SHORT).show();
		} else if (!email.matches(EMAIL_REGEX)) {
			Toast.makeText(this, "Please enter a valid email", Toast.LENGTH_SHORT).show();
		} else {
			// Attempt to register user into database
			int result = RegisterController.registerUser(username, password, name, email);
	
			if (result == RegisterController.REGISTER_SUCCESS) {
				Toast.makeText(this, "Registration successful. Please log in.", Toast.LENGTH_SHORT).show();
				finish();
			} else if (result == RegisterController.USERNAME_INVALID) {
				Toast.makeText(this, "Username :'" + username + "' is not available.", Toast.LENGTH_SHORT).show();
			}
		}
	}

	/**
	 * Switches the layout from create new user back to login when "cancel" is
	 * pressed
	 * 
	 * @param view
	 */
	public void cancelButtonClicked(View view) {
		finish();
	}
}
